import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';
import {
  Button,
  DatePicker,
  Form,
  Input,
  Select,
  Space,
  Switch,
  Table,
  Modal,
  Collapse,
  message,
  Popconfirm,
} from 'antd';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import APIS from '@/apis';
import {FormInstance} from 'antd/lib/form';
import TextArea from 'antd/lib/input/TextArea';
import ImageUpload from '@/components/ImageUpload';
import moment from 'moment';
import VideoUpload from '@/components/VideoUpload';
import {number, string} from 'prop-types';
import locale from 'antd/es/date-picker/locale/zh_CN';
import CourseMemberEditor from './CourseMemberEditor';
import VideoUploadAndSelect from '../../../components/VideoUploadAndSelect/index';
import RichTextEditor from "@/components/RichTextEditor";
import {copyToClip} from "@/utils/utils";

const tailLayout = {
  labelCol: {offset: 1},
};
const idLayout = {
  // wrapperCol: {offset: 1},
  labelCol: {offset: 2},
};

class CreateNewCourse extends Component<any, any> {
  formInstance?: FormInstance | null;

  constructor(props: any) {
    super(props);
    this.state = {
      editorData: null,
      courseTag: [],
      courseType: -1,
      courseMode: -1,
      videoUrl: null,
      imageUrl: null,
      startTime: null,
      endTime: null,
      courseTeachers: [],
      willAddTeacher: {id: -1},

      courseChapters: [],
      courseChaptersList: [],
      chapterVisible: false,
      chapterEditorData: {id: null, chapterName: null, lessonType: null, parent: null},

      chapterCourseIndex: 0,
      chapterCourseVisible: false,
      courseId: -1,
      isCanEdit: false,
      isCanShow: false,
      schoolId: -1,//选择的学校
      collegeId: -1,//选择的学院

      chapterCourseData: {
        id: number,
        chapterId: number,
        description: string,
        lessonName: string,
        lessonIndex: number,
        articleId: number, //文章课程
        lessonAsset: number,
        lessonVideo: number, //视频课程
        expName: string,
        expGuide: string,
        servicePlan: string,
        deviceRequire: string,
        expFeature: string, //虚拟仿真实验课
        teacher: string,
        startTime: {},
        endTime: {}, //直播课
      },

      courseAssetData: [],
      courseDesign: "",
      examStandard: ""
    };
  }

  actionRef: any; //学院名称
  componentWillUnmount() {
    window.onbeforeunload = null;
  }

  componentDidMount() {
    window.onbeforeunload = function (event: any) {
      event.returnValue = "系统不会保存用户数据!";
    };
    APIS.CourseAPI.GetAssetsList({current: 1, pageSize: 99999}).then((res) => {
      this.setState({courseAssetData: res.data});
    });
    var params = new URLSearchParams(this.props.history.location.search);
    var id = null;
    if (params.has('id')) {
      id = parseInt(params.get('id') + '');
      this.setState({courseId: id});
      APIS.CourseAPI.GetCourseDetail({id}).then((data) => {
        //console.log(data.typeInfo);
        this.setState({
          editorData: data,
          courseTag: [],
          courseType: data.typeInfo ? data.typeInfo.id : 0,
          courseMode: data.mode,
          videoUrl: data.video,
          imageUrl: data.courseImg,
          startTime: data.startTime,
          endTime: data.endTime,
          schoolId: data?.collegeInfo?.schoolInfo?.id,
          courseDesign: data.courseDesign,
          examStandard: data.examStandard
        });
        this.requestGetTeacherData(data.id);
        this.requestGetChapterData();
        let user = data;
        this.requestGetUserData(user);
        user = null;
        //将tags转换为tagIds以供组件使用
        var tagIds: any = [];
        data.tags?.map?.((v: any) => {
          tagIds = [...tagIds, v.id];
        });
        this.setState({courseTag: tagIds});
      }).catch(() => {
        message.error("课程信息不存在或者数据错误！");
        this.props.history.replace("teaching/course/list");
      });
    } else {
      this.setState({isCanShow: true, isCanEdit: true});
    }
  }

  requestGetTeacherData(id: number) {
    APIS.CourseAPI.GetAllCourseMember({courseId: id}).then((res) => {
      this.setState({courseTeachers: res});
    });
  }

  requestGetUserData = (data) => {
    APIS.UserAPI.GetCurrentUser().then((resp) => {
      if (resp.id === data.createBy || resp.permissions.includes("ROLE_ADMIN")) {
        // console.log("管理员或创建者");
        this.setState({isCanShow: true});
      } else {
        this.setState({isCanShow: false});
      }
    }).catch(e => {
      console.error(e);
    })
  }

  requestGetChapterData() {
    APIS.CourseAPI.GetChapterList(this.state.editorData).then((res) => {
      this.setState({courseChaptersList: res});
      res?.map?.((v: any, i: any) => {
        (v.key = i), (v.children = []);
      });
      this.setState({courseChapters: this.translateDataToTree(res)});
    });
  }

  translateDataToTree(data: any) {
    let parents: Array<any> = data?.filter((value: any) => value.parent == 'undefined' || value.parent == null);
    let childrens = data?.filter(
      (value: any) => value.parent !== 'undefined' && value.parent != null,
    );
    let translator = (parents: any, childrens: any) => {
      parents?.forEach((parent: any) => {
        childrens?.forEach((current: any, index: any) => {
          if (current.parent === parent.id) {
            let temp = JSON.parse(JSON.stringify(childrens));
            temp.splice(index, 1);
            translator([current], temp);
            typeof parent.children !== 'undefined'
              ? parent.children.push(current)
              : (parent.children = [current]);
          }
        });
        if (parent.children.length === 0) {
          delete parent.children;
        } else {
          parent.children.sort((a: any, b: any) => a.index - b.index);

        }
      });
    };
    translator(parents, childrens);
    parents?.sort((a, b) => a.index - b.index);
    return parents;
  }

  requestGetChapterDetails(data: any) {
    APIS.CourseAPI.GetChapterDetail(data).then((res) => {
      if (res.lessonDetails)
        this.setState({chapterCourseVisible: true, chapterCourseData: res.lessonDetails});
      else
        this.setState({
          chapterCourseVisible: true,
          chapterCourseData: {id: null, chapterId: data.id},
        });
      if (data.lessonType === 3) {
        this.props.history.push({pathname: 'lesson', search: "id=" + data.id});
      }
    });
  }

  columns: any = [
    {
      title: '章节目录',
      dataIndex: 'chapterName',
      key: 'chapterName',
    },
    {
      title: '类型',
      dataIndex: 'lessonType',
      render: (type: number) => {
        switch (type) {
          case 1:
            return '文章课程';
          case 2:
            return '视频课程';
          case 3:
            return '虚拟仿真实验课';
          case 4:
            return '直播课';
          default:
            return '空节点';
        }
      },
    },
    {
      title: '排序',
      render: (data: any) => {
        return <Space>
          <a onClick={() => APIS.CourseAPI.MoveChapter({
            chapterId: data.id,
            dir: 1
          }).then(() => this.requestGetChapterData())}>
            上升
          </a>
          <a onClick={() => APIS.CourseAPI.MoveChapter({
            chapterId: data.id,
            dir: -1
          }).then(() => this.requestGetChapterData())}>
            下降
          </a>
        </Space>
      },
    },
    {
      title: '操作',
      render: (data: any) => {
        return (
          <Space>
            <a onClick={() => this.setState({chapterVisible: true, chapterEditorData: data})}>
              编辑
            </a>
            <Popconfirm title="确定要删除该条记录?"
                        okText="确定"
                        onConfirm={() => {
                          APIS.CourseAPI.DeleteChapter(data).then(() => this.requestGetChapterData())
                        }}
                        cancelText="取消">
              <a>
                删除
              </a>
            </Popconfirm>
            {data.lessonType !== 0 ? (
              <a
                onClick={() => {
                  // this.state.chapterCourseIndex = data.lessonType;

                  this.setState({chapterCourseIndex: data.lessonType});
                  this.requestGetChapterDetails(data);

                }}
              >
                编辑课程
              </a>
            ) : null}
          </Space>
        );
      },
    },
  ];

  private renderCourseInfo() {
    const {RangePicker} = DatePicker;
    // console.log(this.state.editorData);
    return (

      <Collapse.Panel header="课程信息" key="1">
        <Form
          ref={(ref) => this.formInstance = ref}
          style={{marginTop: '20px'}}
          initialValues={{
            name: this.state.editorData?.courseName,
            duration: this.state.editorData?.duration,
            score: this.state.editorData?.score / 100,
            state: this.state.editorData?.state,
            description: this.state.editorData?.description,
            requireFlag: this.state.editorData?.requireFlag,
            template: this.state.editorData?.template,
            ilabAppId: this.state.editorData?.ilabAppId,
            ilabAppSecret: this.state.editorData ? "*******" : "",
            mode: this.state.editorData?.mode,
            coursesCover: this.state.editorData?.courseImg,
            schoolId: this.state.editorData?.collegeInfo?.schoolInfo?.id,
            collegeId: this.state.editorData?.collegeInfo?.id,
            type: this.state.editorData?.typeInfo.id,
            time: this.state.editorData ? [
              moment(this.state.editorData?.startTime),
              moment(this.state.editorData?.endTime),
            ] : null

          }}
          onFinish={(values) => {
            // console.log(values);

            this.state.editorData
              ? APIS.CourseAPI.UpdateCourse({
                id: this.state.editorData.id,
                type: this.state.courseType,
                tagIds: this.state.courseTag,
                mode: this.state.courseMode,
                video: this.state.videoUrl,
                courseImg: this.state.imageUrl,
                startTime: this.state.startTime,
                endTime: this.state.endTime,
                courseName: values.name,
                duration: values.duration,
                score: values.score * 100,
                state: values.state ? 1 : 0,
                description: values.description,
                requireFlag: values.requireFlag ? 1 : 0,
                template: values.template ? 1 : 0,
                school: values.schoolId,
                college: values.collegeId,
                ilabAppId: values.ilabAppId,
                ilabAppSecret: values.ilabAppSecret === "*******" ? this.state.editorData.ilabAppSecret : values.ilabAppSecret,
              }).then((res) => {
                if (res.code === 10000) {
                  alert('修改成功')
                }
              })
              : APIS.CourseAPI.CreateNewCourse({
                courseName: values.name,
                type: values.type,
                tagIds: this.state.courseTag,
                mode: this.state.courseMode,
                video: this.state.videoUrl,
                courseImg: this.state.imageUrl,
                duration: values.duration,
                score: values.score * 100,
                startTime: this.state.startTime,
                endTime: this.state.endTime,
                state: values.state ? 1 : 0,
                description: values.description,
                requireFlag: values.requireFlag ? 1 : 0,
                template: values.template ? 1 : 0,
                school: values.schoolId,
                college: values.collegeId,
                ilabAppId: values.ilabAppId,
                ilabAppSecret: values.ilabAppSecret,
              }).then((res) => {
                console.log(res);
                if (res.code === 10000) {
                  alert('创建成功');
                }
                this.props.history.goBack();
              });
          }}
        >
          <Form.Item
            label="课程名称"
            name="name"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请输入课程名称'}]}
          >
            <Input placeholder="请输入课程名称"/>
          </Form.Item>
          <Form.Item
            name="tag"
            label="课程标签"
            hasFeedback
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: false, message: '请选择课程标签'}]}
          >
            <SearchAbleSelect
              searchData={async (key) => {
                var datas: Array<any> = await APIS.CourseAPI.SearchGetTagList(key);
                return Promise.resolve(
                  datas.map((item) => {
                    return {value: item.id, key: item.tag};
                  }),
                );
              }}
              name="tag"
              values={this.state.courseTag}
              maxCount={3}
              placeholder="请选择标签（最多3个）"
              isMultiple={true}
              getValue={(value) => this.setState({courseTag: value.tag})}
              initialValue={this.state.editorData?.tags.map((item: any) => {
                return item.id;
              })}
            />
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item
            name="mode"
            label="课程形式"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请选择课程形式'}]}
            validateStatus={this.state.courseMode === -1 ? 'error' : 'success'}
          >
            <SearchAbleSelect
              searchData={async (key) => {
                var datas: Array<any> = await APIS.CourseAPI.SearchGetModeList(key);
                return Promise.resolve(
                  datas.map((item) => {
                    return {value: item.id, key: item.modeName};
                  }),
                );
              }}
              getValue={(value) => {
                this.setState({courseMode: value.mode});
                this.formInstance?.setFieldsValue({"mode": value.mode})
              }}
              initialValue={this.state.editorData?.mode}
              disabled={this.state.editorData ? true : false}
              name="mode"
              placeholder="请选择课程形式"

            />
          </Form.Item>
          <br/>
          <div style={{display: 'flex', justifyContent: 'start', width: '100%'}}>
            <Form.Item
              name='video'
              style={{float: 'left'}}
            >
              介绍视频:
              <VideoUpload
                preVideo={this.state.videoUrl}
                handleVideoChange={(url: any) => this.setState({videoUrl: url})}
              />
            </Form.Item>
            <Form.Item
              style={{float: 'left', marginLeft: '200px'}}
              name='coursesCover'
              rules={[{required: true, message: '请上传封面'}]}
            >
              课程封面:
              <ImageUpload
                preImage={this.state.imageUrl}
                handleImageChange={(url: any) => {
                  this.formInstance?.setFieldsValue({"coursesCover": url});
                  this.setState({imageUrl: url});

                }}
              />
            </Form.Item>
          </div>
          <br/>
          <Form.Item
            label="课程学时"
            name="duration"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请输入课程学时'}]}
          >
            <Input placeholder="请输入课程学时" type="number"/>
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="课程学分"
            name="score"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请输入课程学分'}]}
          >
            <Input placeholder="请输入课程学分" type="number"/>
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item label="实验Id"
                     name="ilabAppId"
                     {...idLayout}
                     style={{width: '300px', float: 'left', marginRight: '200px'}}>
            <Input placeholder="请输入实验Id" type="number"/>
          </Form.Item>

          {
            this.state.isCanShow ?
              <div>
                <br/>
                <br/>
                <br/>
                <Form.Item
                  label="实验秘钥"
                  name="ilabAppSecret"
                  {...tailLayout}
                  style={{width: '300px', float: 'left', marginRight: '200px'}}>
                  <Input disabled={!this.state.isCanEdit} placeholder="请输入实验秘钥"/>
                </Form.Item></div> : null
          }
          {
            this.state.editorData && this.state.isCanShow ? <div style={{height: 0}}>
              <Button style={{marginRight: 20}}
                      onClick={() => {
                        this.formInstance.setFieldsValue({"ilabAppSecret": this.state.editorData.ilabAppSecret})
                        this.setState({isCanEdit: true});
                      }
                      }
              >编辑</Button>
              <Button onClick={() => {
                let copy = this.state.editorData.ilabAppSecret;
                copyToClip(copy);
              }}>复制</Button>
            </div> : null
          }
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="课程类型"
            name="type"
            style={{width: '300px', float: 'left'}}
            rules={[{required: true, message: '请选择课程类型'}]}
          >
            <SearchAbleSelect
              searchData={async (key) => {
                var datas: Array<any> = await APIS.CourseAPI.SearchGetTypeList(key);
                return Promise.resolve(
                  datas.map((item) => {
                    return {value: item.id, key: item.typeName};
                  }),
                );
              }}
              name="type"
              values={this.state.courseType > -1 ? this.state.courseType : undefined}
              initialValue={this.state.editorData?.typeInfo?.id}
              placeholder="请选择课程类型"
              getValue={(value) => {
                this.setState({courseType: value.type});

                this.formInstance?.setFieldsValue({"type": value.type})
              }}

            />
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="起止时间"
            name="time"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请选择起止时间'}]}
          >
            <RangePicker
              locale={locale}
              defaultValue={
                this.state.editorData
                  ? [
                    moment(this.state.editorData?.startTime),
                    moment(this.state.editorData?.endTime),
                  ]
                  : null
              }
              onChange={(date, dateString) => {
                this.setState({startTime: dateString[0]});
                this.setState({endTime: dateString[1]});
              }}
            />
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="学校名称"
            name="schoolId"
            style={{width: '300px', float: 'left', marginRight: '200px'}}
            rules={[{required: true, message: '请选择学校'}]}
          >
            <SearchAbleSelect
              searchData={async (key) => {
                var datas: Array<any> = await APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 9999});
                //var datas: Array<any> = await  APIS.OrgsAPI.GetSchoolList({ current: 1, pageSize: 9999 });
                return Promise.resolve(
                  datas.map((item) => {
                    return {value: item.id, key: item.name};
                  }),
                );
              }}
              name="schoolId"
              values={this.state.schoolId > -1 ? this.state.schoolId : undefined}
              initialValue={this.state.editorData?.collegeInfo?.id}
              placeholder="请选择学校"
              getValue={(value) => {
                this.setState({schoolId: value.schoolId});
                this.formInstance?.setFieldsValue({"schoolId": value.schoolId});
                setTimeout(() => {
                  this.actionRef?.onSearch('');
                }, 200);
              }}

            />
          </Form.Item>
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="学院名称"
            name="collegeId"
            style={{width: '300px', float: 'left'}}
            rules={[{required: true, message: '请选择学校'}]}
          >
            <SearchAbleSelect
              disabled={this.state.schoolId === -1 || this.state.schoolId === undefined}
              ref={(ref: any) => {
                this.actionRef = ref
              }}
              searchData={async (key) => {
                try {
                  let datas: Array<any> = await APIS.OrgsAPI.SearchGetCollegeList({id: this.state.schoolId});
                  // console.log(datas);
                  return Promise.resolve(
                    datas.map((item) => {
                      return {value: item.id, key: item.collegeName};
                    }),
                  );
                } catch (e) {
                  console.error(e);
                  return []
                }
              }}
              name="collegeId"
              values={this.state.collegeId > -1 ? this.state.collegeId : undefined}
              initialValue={this.state.editorData?.collegeInfo?.id}
              placeholder="请选择学院"
              getValue={(value) => {
                this.setState({collegeId: value.type});
                this.formInstance?.setFieldsValue({"collegeId": value.collegeId})
              }}

            />
          </Form.Item>
          {/* <Form.Item
            label="课程状态"
            name="state"
            valuePropName="checked"
            style={{ float: 'left' }}
          >
            <Switch />
          </Form.Item> */}
          <br/>
          <br/>
          <br/>
          <Form.Item
            label="课程简介"
            name="description"
            rules={[{required: true, message: '请输入简介'}]}
          >
            <TextArea placeholder="请输入简介" rows={5} style={{width: '720px'}}/>
          </Form.Item>
          <Form.Item
            label="是否必修"
            name="requireFlag"
            valuePropName="checked"
            style={{float: 'left', marginRight: '390px'}}
          >
            <Switch/>
          </Form.Item>
          {/* <Form.Item
            label="是否模板"
            name="template"
            valuePropName="checked"
            style={{ float: 'left' }}
          >
            <Switch />
          </Form.Item> */}
          <br/>
          <br/>
          <br/>
          <br/>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {this.state.editorData ? '修改' : '新增'}
              </Button>
              <Button type="default" htmlType="button" onClick={() => this.props.history.goBack()}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Collapse.Panel>
    );
  }

  /*课程设计*/
  CourseDesign = () => {
    const {courseDesign, courseId} = this.state;
    return <div>
      <RichTextEditor
        ContentInitialValue={courseDesign}
        OnContentChanged={(content) => {
          this.setState({courseDesign: content});
        }}/>
      <div style={{display: "flex", justifyContent: "flex-end"}}>
        <Button
          onClick={() => {
            APIS.CourseAPI.UpdateCourseDesign({id: courseId, courseDesign: courseDesign})
              .then((resp) => {
                if (resp.code === 10000) {
                  message.success("修改成功")
                }
              });
          }}
          style={{marginTop: 5}}
          type={"primary"}>提交</Button>
      </div>
    </div>
  }
  /*考核标准*/
  EvaluationStandard = () => {
    const {examStandard, courseId} = this.state;
    return <div>
      <RichTextEditor
        ContentInitialValue={examStandard}
        OnContentChanged={(content) => {
          this.setState({examStandard: content});
        }}/>
      <div style={{display: "flex", justifyContent: "flex-end"}}>
        <Button
          onClick={() => {
            APIS.CourseAPI.UpdateCourseDesign({id: courseId, examStandard: examStandard})
              .then((resp) => {
                if (resp.code === 10000) {
                  message.success("修改成功")
                }
              });
          }}
          style={{marginTop: 5}}
          type={"primary"}>提交</Button>
      </div>
    </div>
  }

  render() {
    const {RangePicker} = DatePicker;
    return (
      <Collapse accordion ghost>
        {this.renderCourseInfo()}
        <Collapse.Panel header="课程设计" key="2" disabled={!this.state.editorData}>
          {this.state.courseId > 0 ?
            <this.CourseDesign/> : null}
        </Collapse.Panel>
        <Collapse.Panel header="考核标准" key="3" disabled={!this.state.editorData}>
          {this.state.courseId > 0 ?
            <this.EvaluationStandard/> : null}
        </Collapse.Panel>
        <Collapse.Panel header="教学团队" key="4" disabled={!this.state.editorData}>
          {this.state.courseId > 0 ?
            <CourseMemberEditor isShow={true} courseId={this.state.courseId}></CourseMemberEditor> : null}
        </Collapse.Panel>

        <Collapse.Panel header="课程章节" key="5" disabled={!this.state.editorData}>
          <Button
            type="primary"
            style={{float: 'right', zIndex: 10000}}
            onClick={() => this.setState({chapterVisible: true})}
          >
            新增章节
          </Button>
          <Table columns={this.columns} dataSource={this.state.courseChapters}/>

          <Modal
            title="编辑章节"
            visible={this.state.chapterVisible}
            onCancel={() => this.setState({chapterVisible: false, chapterEditorData: null})}
            footer={<div></div>}
          >
            {this.state.chapterVisible && (
              <Form
                initialValues={{
                  name: this.state.chapterEditorData?.chapterName,
                  type: this.state.chapterEditorData?.lessonType,
                  parent: this.state.chapterEditorData?.parent
                    ? this.state.chapterEditorData.parent
                    : null,
                }}
                onFinish={(values) => {
                  if (this.state.chapterEditorData?.id) {
                    APIS.CourseAPI.UpdateChapter({
                      id: this.state.chapterEditorData.id,
                      chapterName: values.name,
                      courseId: this.state.editorData.id,
                      lessonType: values.type,
                      parent: values.parent === -1 ? null : values.parent,
                    }).then(() => {
                      this.setState({chapterVisible: false, chapterEditorData: null});
                      this.requestGetChapterData();
                    });
                  } else {
                    APIS.CourseAPI.CreateNewChapter({
                      chapterName: values.name,
                      courseId: this.state.editorData.id,
                      lessonType: values.type,
                      parent: values.parent === -1 ? null : values.parent,
                    }).then(() => {
                      this.setState({chapterVisible: false});
                      this.requestGetChapterData();
                    });
                  }
                }}
              >
                <Form.Item
                  name="name"
                  label="章节名称"
                  rules={[{required: true, message: '请输入章节名称'}]}
                >
                  <Input/>
                </Form.Item>
                <Form.Item
                  name="type"
                  label="课程类型"
                  rules={[{required: true, message: '请选择测成类型'}]}
                >
                  <Select>
                    <Select.Option value={0}>空节点</Select.Option>
                    <Select.Option value={1}>文章课程</Select.Option>
                    <Select.Option value={2}>视频课程</Select.Option>
                    <Select.Option value={3}>虚拟仿真实验课</Select.Option>
                    <Select.Option value={4}>直播课</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="parent"
                  label="父节点"
                  rules={[{required: true, message: '请选择父节点'}]}
                >
                  <Select
                    placeholder="请选择父节点"
                  >
                    <Select.Option value={-1}>无</Select.Option>
                    {this.state.courseChaptersList.map?.((v: any, i: number) => (
                      <Select.Option key={v.id} value={v.id}>
                        {v.chapterName}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item style={{float: 'right'}}>
                  <Space>
                    <Button
                      type="default"
                      onClick={() =>
                        this.setState({chapterVisible: false, chapterEditorData: null})
                      }
                    >
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            )}
          </Modal>

          <Modal
            title="文章课"
            visible={this.state.chapterCourseVisible && this.state.chapterCourseIndex === 1}
            onCancel={() => this.setState({chapterCourseVisible: false, chapterCourseData: null})}
            footer={<div></div>}
          >
            {this.state.chapterCourseVisible && this.state.chapterCourseIndex === 1 && (
              <Form
                initialValues={{
                  lessonName: this.state.chapterCourseData?.lessonName,
                  lessonIndex: this.state.chapterCourseData?.lessonIndex,
                  articleId: this.state.chapterCourseData?.articleId,
                }}
                onFinish={(values) => {
                  if (this.state.chapterCourseData.id) {
                    APIS.CourseAPI.UpdateChapterCourseArticle({
                      id: this.state.chapterCourseData.id,
                      chapterId: this.state.chapterCourseData.chapterId,
                      articleId: this.state.chapterCourseData.articleId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                    }).then(() => this.setState({chapterCourseVisible: false}));
                  } else {
                    APIS.CourseAPI.CreateNewChapterCourseArticle({
                      chapterId: this.state.chapterCourseData.chapterId,
                      articleId: this.state.chapterCourseData.articleId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                    }).then(() => this.setState({chapterCourseVisible: false}));
                  }
                }}
              >
                <Form.Item
                  label="课程名称"
                  name="lessonName"
                >
                  <Input/>
                </Form.Item>
                <Form.Item
                  label="关联文章"
                  name="articleId"
                >
                  <SearchAbleSelect
                    searchData={async (key) => {
                      var datas: Array<any> = await APIS.ArticleAPI.SearchGetArticle(key);
                      return Promise.resolve(
                        datas.map((item) => {
                          return {value: item.id, key: item.title};
                        }),
                      );
                    }}
                    name="title"
                    placeholder="请选择关联文章"
                    getValue={(value) => (this.state.chapterCourseData.articleId = value.title)}
                    initialValue={this.state.chapterCourseData.articleId}

                    //2020.12.22修改
                    style={{width: 280, marginRight: 30}}

                  />
                  {/* 2020.12.22修改 */}
                  <Button onClick={() => this.props.history.push("/article/create")}>新增文章</Button>


                </Form.Item>

                <Form.Item style={{float: 'right'}}>
                  <Space>
                    <Button
                      onClick={() =>
                        this.setState({chapterCourseVisible: false, chapterCourseData: null})
                      }
                    >
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            )}
          </Modal>

          <Modal
            title="视频课"
            visible={this.state.chapterCourseVisible && this.state.chapterCourseIndex === 2}
            onCancel={() => this.setState({chapterCourseVisible: false, chapterCourseData: null})}
            footer={<div></div>}
          >
            {this.state.chapterCourseVisible && this.state.chapterCourseIndex === 2 && (
              <Form
                initialValues={{
                  lessonName: this.state.chapterCourseData?.lessonName,
                  lessonIndex: this.state.chapterCourseData?.lessonIndex,
                  description: this.state.chapterCourseData?.description,
                  teacher: this.state.chapterCourseData?.teacher,
                  lessonAsset: this.state.chapterCourseData?.lessonAsset,
                  lessonVideo: this.state.chapterCourseData?.lessonVideo,
                }}
                onFinish={(values) => {
                  if (this.state.chapterCourseData.id) {
                    APIS.CourseAPI.UpdateChapterCourseVideo({
                      id: this.state.chapterCourseData.id,
                      chapterId: this.state.chapterCourseData.chapterId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                      description: values.description,
                      teacher: values.teacher,
                      lessonAsset: values.lessonAsset,
                      lessonVideo: values.lessonVideo,
                    }).then(() => {
                      this.setState({chapterCourseVisible: false});
                      ;message.success("修改成功")
                    });
                  } else {
                    APIS.CourseAPI.CreateNewChapterCourseVideo({
                      chapterId: this.state.chapterCourseData.chapterId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                      description: values.description,
                      teacher: values.teacher,
                      lessonAsset: values.lessonAsset,
                      lessonVideo: values.lessonVideo,
                    }).then(() => {
                      this.setState({chapterCourseVisible: false});
                      message.success("创建成功")
                    });
                  }
                }}
              >
                <Form.Item label="课程名称" name="lessonName">
                  <Input/>
                </Form.Item>
                <Form.Item label="课程简介" name="description">
                  <Input/>
                </Form.Item>
                <Form.Item label="课程老师" name="teacher">
                  <Select>
                    {this.state.courseTeachers.map?.((v: any) => (
                      <Select.Option key={v.id} value={v.id}>
                        {v.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item label="文档课件" name="lessonAsset">
                  <Select>
                    {this.state.courseAssetData.map((v: any, i: number) => {
                      if (v.type === 1)
                        return (
                          <Select.Option value={v.id} key={i}>
                            {v.name}
                          </Select.Option>
                        );
                      else return null;
                    })}
                  </Select>
                </Form.Item>
                <Form.Item label="视频课件" name="lessonVideo">
                  <VideoUploadAndSelect
                    handleVideoChange={(url: any) => console.log(url)}
                  />
                </Form.Item>
                <Form.Item style={{float: 'right'}}>
                  <Space>
                    <Button
                      onClick={() =>
                        this.setState({chapterCourseVisible: false, chapterCourseData: null})
                      }
                    >
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            )}
          </Modal>

          <Modal
            title="直播课"
            visible={this.state.chapterCourseVisible && this.state.chapterCourseIndex === 4}
            onCancel={() => this.setState({chapterCourseVisible: false, chapterCourseData: null})}
            footer={<div></div>}
          >
            {this.state.chapterCourseVisible && this.state.chapterCourseIndex === 4 && (
              <Form
                initialValues={{
                  lessonName: this.state.chapterCourseData?.lessonName,
                  lessonIndex: this.state.chapterCourseData?.lessonIndex,
                  description: this.state.chapterCourseData?.description,
                  teacher: this.state.chapterCourseData?.teacher,
                  startTime: this.state.chapterCourseData?.startTime,
                  endTime: this.state.chapterCourseData?.endTime,
                }}
                onFinish={(values) => {
                  if (this.state.chapterCourseData.id) {
                    APIS.CourseAPI.UpdateChapterCourseLiving({
                      id: this.state.chapterCourseData.id,
                      chapterId: this.state.chapterCourseData.chapterId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                      description: values.description,
                      teacher: values.teacher,
                      startTime: this.state.chapterCourseData.startTime,
                      endTime: this.state.chapterCourseData.endTime,
                    }).then(() => this.setState({chapterCourseVisible: false}));
                  } else {
                    APIS.CourseAPI.CreateNewChapterCourseLiving({
                      chapterId: this.state.chapterCourseData.chapterId,
                      lessonIndex: values.lessonIndex,
                      lessonName: values.lessonName,
                      description: values.description,
                      teacher: values.teacher,
                      startTime: this.state.chapterCourseData.startTime,
                      endTime: this.state.chapterCourseData.endTime,
                    }).then(() => this.setState({chapterCourseVisible: false}));
                  }
                }}
              >
                <Form.Item label="课程名称" name="lessonName">
                  <Input/>
                </Form.Item>
                <Form.Item label="课程简介" name="description">
                  <Input/>
                </Form.Item>
                <Form.Item label="课程老师" name="teacher">
                  <Select>
                    {this.state.allTeachers.map?.((v: any) => (
                      <Select.Option key={v.id} value={v.id}>
                        {v.name}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>

                <Form.Item label="起止时间" name="time">
                  <RangePicker
                    defaultValue={
                      this.state.chapterCourseData.id !== null
                        ? [
                          moment(this.state.chapterCourseData.startTime),
                          moment(this.state.chapterCourseData.endTime),
                        ]
                        : null
                    }
                    onChange={(date, dateString) => {
                      this.state.chapterCourseData.startTime = moment(dateString[0]);
                      this.state.chapterCourseData.endTime = moment(dateString[1]);
                    }}
                    showTime
                  />
                </Form.Item>
                <Form.Item style={{float: 'right'}}>
                  <Space>
                    <Button
                      onClick={() =>
                        this.setState({chapterCourseVisible: false, chapterCourseData: null})
                      }
                    >
                      取消
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                  </Space>
                </Form.Item>
              </Form>
            )}
          </Modal>
        </Collapse.Panel>
      </Collapse>
    );
  }
}

export default connect()(CreateNewCourse);
